package com.demo.petshop.service.impl;

import com.demo.petshop.entity.Favorites;
import com.demo.petshop.entity.Stores;
import com.demo.petshop.mapper.FavoritesMapper;
import com.demo.petshop.mapper.ProductsMapper;
import com.demo.petshop.mapper.StoresMapper;
import com.demo.petshop.mapper.VideosMapper;
import com.demo.petshop.service.FavoritesService;
import com.demo.petshop.util.Result;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.sqlite.date.DateFormatUtils;

import java.util.Date;

import static com.demo.petshop.entity.table.FavoritesTableDef.FAVORITES;
import static com.demo.petshop.entity.table.ProductsTableDef.PRODUCTS;
import static com.demo.petshop.entity.table.StoresTableDef.STORES;
import static com.demo.petshop.entity.table.UsersTableDef.USERS;
import static com.demo.petshop.entity.table.VideosTableDef.VIDEOS;

/**
 * 服务层实现。
 *
 * @author lenovo
 * @since 2025-06-11
 */
@Service
public class FavoritesServiceImpl extends ServiceImpl<FavoritesMapper, Favorites> implements FavoritesService {
    @Autowired
    private FavoritesMapper favoritesMapper;
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private VideosMapper videosMapper;
    @Autowired
    private StoresMapper storesMapper;

    private String video = "video";
    private String product = "product";
    private String store = "store";

    private String updateAt = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");

    private int getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getUserId();
    }

    @Override
    public Object addFavorite(String type, int id) {
        int userId = getUserId();
        Favorites favorites = new Favorites();
        favorites.setUserId(userId);
        if (product.equals(type)) {
            favorites.setProductId(id);
            favorites.setVideoId(0);
            favorites.setStoreId(0);
            favorites.setType(product);
        } else if (video.equals(type)) {
            favorites.setProductId(0);
            favorites.setVideoId(id);
            favorites.setStoreId(0);
            favorites.setType(video);
        } else {
            favorites.setProductId(0);
            favorites.setVideoId(0);
            favorites.setStoreId(id);
            favorites.setType(store);
            Stores stores = storesMapper.selectOneById(id);
            stores.setFollowerCount(stores.getFollowerCount() + 1);
            storesMapper.update(stores);
        }
        favorites.setCreatedAt(updateAt);
        return Result.success(favoritesMapper.insert(favorites));
    }

    @Override
    public Object removeFavorite(String type,int id) {
        int userId = getUserId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.from(FAVORITES).where(FAVORITES.USER_ID.eq(userId).and(FAVORITES.TYPE.eq(type)));

        // 根据类型选择正确的字段进行匹配
        if (product.equals(type)) {
            queryWrapper.and(FAVORITES.PRODUCT_ID.eq(id));
        } else if (video.equals(type)) {
            queryWrapper.and(FAVORITES.VIDEO_ID.eq(id));
        } else if (store.equals(type)) {
            queryWrapper.and(FAVORITES.STORE_ID.eq(id));
            Stores stores = storesMapper.selectOneById(id);
            stores.setFollowerCount(stores.getFollowerCount() - 1);
            storesMapper.update(stores);
        }
        return Result.success(favoritesMapper.deleteByQuery(queryWrapper));
    }

    @Override
    public Object getFavorite(String type) {
        int userId = getUserId();
        return getFavoriteInternal(type, userId);
    }

    @Override
    public Object getFavorite(String type, Integer userId) {
        // 如果userId为null，则使用当前登录用户
        if (userId == null) {
            return getFavorite(type);
        }
        return getFavoriteInternal(type, userId);
    }

    // 内部方法，根据userId和type获取收藏
    private Object getFavoriteInternal(String type, int userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (product.equals(type)) {
            queryWrapper
                    .select(PRODUCTS.ALL_COLUMNS,STORES.NAME.as("storeName"))
                    .from(PRODUCTS)
                    .join(FAVORITES).on(FAVORITES.PRODUCT_ID.eq(PRODUCTS.PRODUCT_ID))
                    .join(STORES).on(STORES.STORE_ID.eq(PRODUCTS.STORE_ID))
                    .where(FAVORITES.USER_ID.eq(userId));
            return Result.success(productsMapper.selectListByQuery(queryWrapper));
        } else if (video.equals(type)) {
            queryWrapper
                    .select(VIDEOS.ALL_COLUMNS,USERS.USERNAME.as("authorName"))
                    .from(VIDEOS)
                    .join(FAVORITES).on(FAVORITES.VIDEO_ID.eq(VIDEOS.VIDEO_ID))
                    .join(USERS).on(USERS.USER_ID.eq(VIDEOS.AUTHOR_ID))
                    .where(FAVORITES.USER_ID.eq(userId));
            return Result.success(videosMapper.selectListByQuery(queryWrapper));
        } else {
            queryWrapper
                    .select(STORES.ALL_COLUMNS)
                    .from(STORES)
                    .join(FAVORITES).on(FAVORITES.STORE_ID.eq(STORES.STORE_ID))
                    .where(FAVORITES.USER_ID.eq(userId));
            return Result.success(storesMapper.selectListByQuery(queryWrapper));
        }
    }

    @Override
    public Object checkFavorite(String type, int id) {
        int userId = getUserId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper
                .from(FAVORITES)
                .where(FAVORITES.TYPE.eq(type).and(FAVORITES.PRODUCT_ID.eq(id)).and(FAVORITES.USER_ID.eq(userId)))
                .or(FAVORITES.TYPE.eq(type).and(FAVORITES.VIDEO_ID.eq(id)).and(FAVORITES.USER_ID.eq(userId)))
                .or(FAVORITES.TYPE.eq(type).and(FAVORITES.STORE_ID.eq(id)).and(FAVORITES.USER_ID.eq(userId)));
        return Result.success(favoritesMapper.selectOneByQuery(queryWrapper));
    }

    @Override
    public Object getCount() {
        int userId = getUserId();
        return getCountInternal(userId);
    }

    @Override
    public Object getCount(Integer userId) {
        // 如果userId为null，则使用当前登录用户
        if (userId == null) {
            return getCount();
        }
        return getCountInternal(userId);
    }

    // 内部方法，根据userId获取收藏数量
    private Object getCountInternal(int userId) {
        // 查询该用户的所有收藏数量
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper
                .from(FAVORITES)
                .where(FAVORITES.USER_ID.eq(userId));
        long count = favoritesMapper.selectCountByQuery(queryWrapper);
        return Result.success(count);
    }

    @Override
    public Object getFavoriteNumber(String type,int id){
        QueryWrapper queryWrapper =new QueryWrapper();
        queryWrapper
                .from(FAVORITES)
                .where(FAVORITES.TYPE.eq(type).and(FAVORITES.PRODUCT_ID.eq(id)))
                .or(FAVORITES.TYPE.eq(type).and(FAVORITES.VIDEO_ID.eq(id)))
                .or(FAVORITES.TYPE.eq(type).and(FAVORITES.STORE_ID.eq(id)));
        return Result.success(favoritesMapper.selectListByQuery(queryWrapper).size());
    }
}
